package com.yinhai.msg.email.tool;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 时间日期工具类
 * 
 * @author huangyh@yinhai.com
 * 
 */
public class DateUtil {
	/**
	 * 默认日期格式 //Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]
	 */
	private static final String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss";

	/**
	 * 默认构造函数
	 */
	private DateUtil() {
	}

	/**
	 * 字符串转换成日期 如果转换格式为空，则利用默认格式进行转换操作
	 * 
	 * @param str
	 *            字符串
	 * @param format
	 *            日期格式
	 * @return 日期
	 * @throws ParseException
	 */
	public static Date str2Date(String str, String format) {
		if (null == str || "".equals(str)) {
			return null;
		}
		// 如果没有指定字符串转换的格式，则用默认格式进行转换
		if (null == format || "".equals(format)) {
			format = DEFAULT_FORMAT;
		}
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		Date date = null;
		try {
			date = sdf.parse(str);
			return date;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static java.sql.Date date2Sql(Date date) {
		if (date != null) {
			if (date instanceof java.sql.Date) {
				return (java.sql.Date) date;
			}
			return new java.sql.Date(date.getTime());
		}
		return null;
	}

	/**
	 * 日期转换为字符串
	 * 
	 * @param date
	 *            日期
	 * @param format
	 *            日期格式
	 * @return 字符串
	 */
	public static String date2Str(Date date, String format) {
		if (null == date) {
			return null;
		}
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.format(date);
	}

	public static String date2Str(Date date) {
		if (null == date) {
			return null;
		}
		SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_FORMAT);
		return sdf.format(date);
	}

	/**
	 * 时间戳转换为字符串
	 * 
	 * @param time
	 * @return
	 */
	public static String timestamp2Str(Timestamp time) {
		Date date = null;
		if (null != time) {
			date = new Date(time.getTime());
		}
		return date2Str(date, DEFAULT_FORMAT);
	}

	public static String timestamp2Str(Timestamp time, String format) {
		Date date = null;
		if (null != time) {
			date = new Date(time.getTime());
		}
		return date2Str(date, format);
	}

	/**
	 * 字符串转换时间戳
	 * 
	 * @param str
	 * @return
	 */
	public static Timestamp str2Timestamp(String str) {
		Date date = str2Date(str, DEFAULT_FORMAT);
		AssertUtil.isTrue(date == null,"操作错误：传入时间为空");
		return new Timestamp(date.getTime());
	}

	/**
	 * 字符串转换时间戳
	 * 
	 * @param str
	 * @param format
	 * @return
	 */
	public static Timestamp str2Timestamp(String str, String format) {
		Date date = str2Date(str, format);
		AssertUtil.isTrue(date == null,"操作错误：传入时间为空");
		return new Timestamp(date.getTime());
	}

	/**
	 * 打印日期字符格式（yyyy-MM-dd hh:mm:ss）
	 * 
	 * @param longValue
	 * @return
	 */
	public static String long2Str(Long longValue) {
		SimpleDateFormat format = new SimpleDateFormat(DEFAULT_FORMAT);
		return format.format(parseDate(longValue));
	}

	public static String long2Str(Long longValue, String format) {
		SimpleDateFormat sFormat = new SimpleDateFormat(format);
		return sFormat.format(parseDate(longValue));
	}

	public static Timestamp long2Timestamp(Long longValue) {
		return new Timestamp(longValue);
	}

	/**
	 * long解析为java.util.Date
	 * 
	 * @param longValue
	 * @return
	 */
	public static Date parseDate(long longValue) {
		return new Date(longValue);
	}

	/**
	 * 判断两个java.util.Date是否为同一天
	 * 
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static boolean isSameDay(Date date1, Date date2) {
		return date1.getDate() == date2.getDate();
	}

	/**
	 * 计算两个long（秒）之间相差的天数
	 * 
	 * @param longValue1
	 * @param longValue2
	 * @return
	 */
	public static int getBetweenDays(long longValue1, long longValue2) {
		long betweenDays = ((longValue1 - longValue2) / 1000) / (60 * 60 * 24);
		return Math.abs((int) betweenDays);
	}

	/**
	 * @Description: 计算2个日期Str的天数
	 * @update: 2014-1-8 by huangyh
	 * @param time1
	 * @param time2
	 * @return
	 */
	public static int getBetweenDays(String time1, String time2) {
		long betweenDays = 0;
		SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date date1 = ft.parse(time1);
			Date date2 = ft.parse(time2);
			betweenDays = date1.getTime() - date2.getTime();
			betweenDays = betweenDays / 1000 / 60 / 60 / 24;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return Math.abs((int) betweenDays);
	}

	/**
	 * sql.Date转化为sql.Timestamp
	 * 
	 * @param date
	 * @return
	 */
	public static Timestamp convertDate2Timestamp(Date date) {
		return new Timestamp(date.getTime());
	}

	/**
	 * @Description: 获取下一天
	 * @update: 2016年1月5日 by huangyh
	 * @param date
	 * @param days
	 * @return
	 */
	public static Timestamp getNextDay(Timestamp date, int days) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(calendar.DATE, days);// 把日期往后增加一天.整数往后推,负数往前移动
		return convertDate2Timestamp(calendar.getTime());
	}

	/**
	 * @Description: 比较两个日期的大小
	 * @update: 2014年8月4日 by huangyh
	 * @param date1
	 * @param date2
	 * @param format
	 * @return
	 */
	public static int compareDate(String date1, String date2, String format) {
		if (ObjectUtil.isEmpty(format)) {
			format = DEFAULT_FORMAT;
		}
		DateFormat df = new SimpleDateFormat(format);
		try {
			Date dt1 = df.parse(date1);
			Date dt2 = df.parse(date2);
			if (dt1.getTime() > dt2.getTime()) {
				return 1;
			} else if (dt1.getTime() < dt2.getTime()) {
				return -1;
			} else {
				return 0;
			}
		} catch (Exception exception) {
			exception.printStackTrace();
		}
		return 0;
	}

	public static int compareDate(Timestamp t1, Timestamp t2) {
		if (t1 == null || t2 == null) {
			return 0;
		}
		if (t1.getTime() > t2.getTime()) {
			return 1;
		}
		return -1;
	}

	public static Date addDay(Date date, int days) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DATE, days);
		return cal.getTime();
	}

	/**
	 * 根据生日和当前时间计算年龄
	 *
	 * @Description
	 * @param birthday
	 * @param nowDay
	 * @return
	 */
	public static Integer getAgeByBirth(Timestamp birthday, Timestamp nowDay) {
		int age = 0;
		try {
			Calendar now = Calendar.getInstance();
			now.setTime(nowDay);// 当前时间

			Calendar birth = Calendar.getInstance();
			birth.setTime(birthday);

			if (birth.after(now)) {// 如果传入的时间，在当前时间的后面，返回0岁
				age = 0;
			} else {
				age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
				if (now.get(Calendar.DAY_OF_YEAR) > birth.get(Calendar.DAY_OF_YEAR)) {
					age += 1;
				}
			}
			return age;
		} catch (Exception e) {// 兼容性更强,异常后返回数据
			return 0;
		}
	}

	/**
	 * 计算年龄
	 * @param birthDay
	 * @return
	 */
	public static int getAge(Date birthDay) {
		Calendar cal = Calendar.getInstance();
		try {
			if (cal.before(birthDay)) {
				return 0;
			}
			int yearNow = cal.get(Calendar.YEAR);
			int monthNow = cal.get(Calendar.MONTH);
			int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
			cal.setTime(birthDay);

			int yearBirth = cal.get(Calendar.YEAR);
			int monthBirth = cal.get(Calendar.MONTH);
			int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

			int age = yearNow - yearBirth;

			if (monthNow <= monthBirth) {
				if (monthNow == monthBirth) {
					if (age > 0) {// 原本计算年龄这里不需要等于，现特殊需求，同月同天算在内，即跨年的时候才这样
						if (dayOfMonthNow <= dayOfMonthBirth) {
							age--;
						}
					}
				} else {
					age--;
				}
			}
			return age;
		} catch (Exception e) {
			return 0;
		}
	}
}
